package com.soriya.nestlive.repository

import com.soriya.nestlive.model.Channel
import com.soriya.nestlive.model.ResponseResult
import com.soriya.nestlive.net.ChannelApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import javax.inject.Inject

class ChannelRepository @Inject constructor(
    private val channelApi: ChannelApi
) {

    fun getMyChannel(): Flow<ResponseResult> = flow {
        emit(ResponseResult.Loading)
        emit(channelApi.getMyChannel())
    }.catch {
        it.printStackTrace()
        emit(ResponseResult.Failed)
    }.flowOn(Dispatchers.IO)

    fun createChannel(channel: Channel): Flow<ResponseResult> = flow {
        emit(ResponseResult.Loading)
        emit(channelApi.createChannel(channel))
    }.catch {
        it.printStackTrace()
        emit(ResponseResult.Failed)
    }.flowOn(Dispatchers.IO)

    fun getFollowedChannelList(userId: Long, page: Int? = null, size: Int? = null): Flow<ResponseResult> = flow {
        emit(ResponseResult.Loading)
        emit(channelApi.getFollowedChannelList(userId, page, size))
    }.catch {
        it.printStackTrace()
        emit(ResponseResult.Failed)
    }.flowOn(Dispatchers.IO)

    fun getById(id: Long): Flow<ResponseResult> = flow {
        emit(ResponseResult.Loading)
        emit(channelApi.getById(id))
    }.catch {
        it.printStackTrace()
        emit(ResponseResult.Failed)
    }.flowOn(Dispatchers.IO)

    fun follow(id: Long): Flow<ResponseResult> = flow {
        emit(ResponseResult.Loading)
        emit(channelApi.follow(id))
    }.catch {
        it.printStackTrace()
        emit(ResponseResult.Failed)
    }.flowOn(Dispatchers.IO)

}